<?php

namespace app\api\controller;

use app\admin\model\cms\AlbumModel;
use app\admin\model\cms\Channels;
use app\admin\model\cms\Diyform;
use app\admin\model\cms\LiveCategoryModel;
use app\admin\model\cms\OrderModel;
use app\admin\model\cms\Plate;
use app\admin\model\cms\Platepost;
use app\admin\model\cms\PlazaCategorymodel;
use app\admin\model\cms\PlazaPostModel;
use app\admin\model\cms\VideoCategoryModel;
use app\admin\model\Investment;
use app\admin\model\InvestmentCategoryModel;
use app\admin\model\UserGroup;
use app\common\controller\Api;
use app\common\model\ChartParent;
use app\common\model\Config;
use Endroid\QrCode\QrCode;
use think\Log;
use think\Model;
use think\Request;
use Yansongda\Pay\Pay;

/**
 * 会员订单控制器
 * Class Order
 * @package app\api\controller
 */
class Order extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];
    //无需鉴权的方法,但需要登录 *表示全部
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    //订单列表
    public function list()
    {
        $request = $this->request->param();
        $user = $this->auth->getUser();//用户信息
        $limit = $request['limit'] ?? 10;//每页数量
        $page = $request['page'] ?? 1;//页码
        $goods_type = $request['goods_type'] ?? '';//商品类型|categories:栏目,articles:文章,user_group:会员分组,album:专辑
        $pay_status = $request['pay_status'] ?? '1';//订单支付状态|默认0:未支付,1:已支付,'all'=>全部

        $data = OrderModel::where('user_id', $user['id']);
        if ($goods_type) {
            $data = $data->where('goods_type', $goods_type);
        }

        if($pay_status != 'all'){
            $data = $data->where('pay_status',$pay_status);
        }

        $data = $data->order('id', 'desc')
            ->paginate($limit, false, ['page' => $page]);
        $res_data = $data->toArray();
        $res = [
            'total'=>$res_data['total'],
            'list'=>$res_data['data'],
        ];
        $this->success('success', $res);
    }

    //订单详情
    public function show(){
        $request = $this->request->param();
        $user = $this->auth->getUser();//用户信息
        $order_id = $request['order_id'];
        $data = OrderModel::where('id',$order_id)->where('user_id',$user['id'])->find();
        if (!$data){
            $this->error('订单不存在');
        }
        $this->success('success',$data->toArray());
    }

    //创建订单
    public function create(){
        $request = $this->request->param();
        $user = $this->auth->getUser();//用户信息
        $pay_type = $this->request->param('pay_type','1');//支付方式|1:微信扫码支付,2:积分,3:临时申请订单(不用付费,只要后台管理员同意就行),5=小程序支付
        $goods_type = $request['goods_type'] ?? '';//商品类型|categories:栏目,articles:文章,user_group:会员分组,album:专辑
        $table_name = $request['table_name'] ?? '';//商品来源的表名|不带表名前缀|plate=论坛分类,plate_post=论坛-帖子表,plaza_category=广场-分类表,plaza_post=广场-帖子表,live_category=直播-分类表,live=直播表,video_category=音视频-分类,video=音视频,user_group=用户(会员)分组,album=专辑,chart_parent=量化辅助分类,pro_diyform=量化辅助内容,investment_category=数据库-分类
        $goods_id = $request['goods_id'] ?? '';//商品相关id|table_name表名下的id值,如果是分类则传过来的是Channels表二级分类的id
        if (!$goods_type || !$table_name || !$goods_id){
            $this->error('缺少参数');
        }

        //获取商品来源
        $table_name_list = OrderModel::TableName;
        $list = [];
        foreach($table_name_list as $k=>$v){
            $list[] = $k;
        }
        //判断商品来源是否正确
        if (!in_array($table_name, $list)) {
            $this->error('商品来源不正确');
        }

        switch ($table_name) {
            case 'plate':
                $model = new Plate();
                $goods_id = Channels::where('id',$goods_id)->value('correlation_id');
                break;
            case 'plate_post':
                $model = new Platepost();
                break;
            case 'plaza_category':
                $model = new PlazaCategorymodel();
                $goods_id = Channels::where('id',$goods_id)->value('correlation_id');
                break;
            case 'plaza_post':
                $model = new PlazaPostModel();
                break;
            case 'live_category':
                $model = new LiveCategoryModel();
                $goods_id = Channels::where('id',$goods_id)->value('correlation_id');
                break;
            case 'live':
                $model = new \app\admin\model\cms\Live();
                break;
            case 'video_category':
                $model = new VideoCategoryModel();
                $goods_id = Channels::where('id',$goods_id)->value('correlation_id');
                break;
            case 'video':
                $model = new \app\admin\model\cms\Video();
                break;
            case 'user_group':
                $model = new UserGroup();
                break;
            case 'album':
                $model = new AlbumModel();
                break;
            case 'chart_parent':
                $model = new ChartParent();
                 $goods_id = Channels::where('id',$goods_id)->value('correlation_id');
                break;
            case 'pro_diyform':
                $model = new Diyform();
                break;
            case 'investment_category':
                $model = new InvestmentCategoryModel();
                 $goods_id = Channels::where('id',$goods_id)->value('correlation_id');
                break;
            default:
                $this->error('商品类型有误');
        }


        $model_data = $model->where('id',$goods_id)->find();
        if (!$model_data){
            $this->error('商品信息有误');
        }

        if ($table_name == 'user_group'){
            $model_data['membership_duration'] = $model_data['membership_expiry'];//会员天数
        }

        //如果是积分购买
        if ($pay_type == 2){
            //查询用户积分余额
            $score = \app\admin\model\User::where('id',$user['id'])->value('score');
            //查配置项1元=多少积分
            $score_exchange_rate = Config::where('name','score_exchange_rate')->value('value');
            //判断积分是否足够支付订单,不足则返回错误
            if ($score_exchange_rate <= 0) {
                $this->error('积分配置不正确');
            }
            //需要花费的积分
            $model_data['membership_price'] = bcmul($model_data['membership_price'],$score_exchange_rate,2);
            if ($score < $model_data['membership_price']){
                $this->error('积分不足');
            }
        }

        $time = time();
        $rand = rand(111,999);
        $data = [
            'user_id'=>$user['id'],
            'goods_type'=>$goods_type,
            'table_name'=>$table_name,
            'goods_id'=>$goods_id,
            'pay_type'=>$pay_type,
            'order_num'=>"{$time}{$rand}{$user['id']}",
            'price'=>$model_data['membership_price'],
            'membership_duration'=>$model_data['membership_duration'],
            'createtime'=>date('Y-m-d H:i:s'),
        ];

        $order_id = OrderModel::insertGetId($data);
        $this->success('success',['order_id'=>$order_id]);
    }

    //购买详情(创建订单前请求)
    public function goodsShow(){
        $goods_type = $this->request->param('goods_type','');//商品类型|categories:栏目,articles:文章,user_group:会员分组,album:专辑
        $table_name = $this->request->param('table_name','');//商品来源的表名|不带表名前缀|plate=论坛分类,plate_post=论坛-帖子表,plaza_category=广场-分类表,plaza_post=广场-帖子表,live_category=直播-分类表,live=直播表,video_category=音视频-分类,video=音视频,user_group=用户(会员)分组,album=专辑,chart_parent=量化辅助分类,pro_diyform=量化辅助内容,investment_category=数据库-分类
        $goods_id = $this->request->param('goods_id','');//商品相关id|table_name表名下的id值,如果是分类则传过来的是Channels表二级分类的id
        if (!$goods_type || !$table_name || !$goods_id){
            $this->error('缺少参数');
        }

        $user_id = $this->auth->getUser()['id'];//用户id

        //获取商品来源
        $table_name_list = OrderModel::TableName;
        $list = [];
        foreach($table_name_list as $k=>$v){
            $list[] = $k;
        }
        //判断商品来源是否正确
        if (!in_array($table_name, $list)) {
            $this->error('商品来源不正确');
        }

        switch ($table_name) {
            case 'plate':
                $model = new Plate();
                $goods_id = Channels::where('id',$goods_id)->value('correlation_id');
                $name = '购买当前栏目';
                break;
            case 'plate_post':
                $model = new Platepost();
                $name = '购买当前内容';
                break;
            case 'plaza_category':
                $model = new PlazaCategorymodel();
                $goods_id = Channels::where('id',$goods_id)->value('correlation_id');
                $name = '购买当前栏目';
                break;
            case 'plaza_post':
                $model = new PlazaPostModel();
                $name = '购买当前内容';
                break;
            case 'live_category':
                $model = new LiveCategoryModel();
                $goods_id = Channels::where('id',$goods_id)->value('correlation_id');
                $name = '购买当前栏目';
                break;
            case 'live':
                $model = new \app\admin\model\cms\Live();
                $name = '购买当前内容';
                break;
            case 'video_category':
                $model = new VideoCategoryModel();
                $goods_id = Channels::where('id',$goods_id)->value('correlation_id');
                $name = '购买当前栏目';
                break;
            case 'video':
                $model = new \app\admin\model\cms\Video();
                $name = '购买当前内容';
                break;
            case 'user_group':
                $model = new UserGroup();
                $name = '购买当前会员';
                break;
            case 'album':
                $model = new AlbumModel();
                $name = '购买当前专辑';
                break;
            case 'chart_parent':
                $model = new ChartParent();
                $goods_id = Channels::where('id',$goods_id)->value('correlation_id');
                $name = '购买当前栏目';
                break;
            case 'pro_diyform':
                $model = new Diyform();
                $name = '购买当前内容';
                break;
            case 'investment_category':
                $model = new InvestmentCategoryModel();
                $goods_id = Channels::where('id',$goods_id)->value('correlation_id');
                $name = '购买当前栏目';
                break;
            default:
                $this->error('类型不正确');
        }

        if (!$goods_id){
            $this->error('商品信息有误');
        }

        $model_data = $model->where('id',$goods_id)->find();
        if (!$model_data){
            $this->error('商品信息有误');
        }

        if ($table_name == 'user_group'){
            $model_data['membership_duration'] = $model_data['membership_expiry'];//会员天数
        }

        //判断当前内容免费,直接看当前分类是否收费
        if (in_array($table_name,['plaza_post','plate_post','live','video','album','pro_diyform']) && (float)$model_data['membership_duration'] <= 0.01){
            switch ($table_name) {
                case 'plate_post':
                    $model = new Plate();
                    $name = '购买当前栏目';
                    $model_data = $model->where('id', $model_data['plateid'])->find();
                    $goods_id = Channels::where('parent_id', '3')
                        ->where('correlation_id', $model_data['id'])
                        ->value('id');
                    $table_name = 'plate';
                    break;
                case 'plaza_post':
                    $model = new PlazaCategorymodel();
                    $name = '购买当前栏目';
                    $model_data = $model->where('id', $model_data['plaza_category_id'])->find();
                    $goods_id = Channels::where('parent_id', '1')
                        ->where('correlation_id', $model_data['id'])
                        ->value('id');
                    $table_name = 'plaza_category';
                    break;
                case 'live':
                    $model = new LiveCategoryModel();
                    $name = '购买当前栏目';
                    $model_data = $model->where('id', $model_data['live_category_id'])->find();
                    $goods_id = Channels::where('parent_id', '6')
                        ->where('correlation_id', $model_data['id'])
                        ->value('id');
                    $table_name = 'live_category';
                    break;
                case 'video':
                    $model = new VideoCategoryModel();
                    $name = '购买当前栏目';
                    $model_data = $model->where('id', $model_data['video_category_id'])->find();
                    $table_name = 'video_category';
                    $goods_id = Channels::where('parent_id', '4')
                        ->where('correlation_id', $model_data['id'])
                        ->value('id');
                    break;
                case 'album':
                    $model = new VideoCategoryModel();
                    $name = '购买当前栏目';
                    $model_data = $model->where('id', $model_data['category_id'])->find();
                    $table_name = 'video_category';
                    $goods_id = Channels::where('parent_id', '4')
                        ->where('correlation_id', $model_data['id'])
                        ->value('id');
                    break;
                default:
                    $this->error('当前分类不可购买,只能购买会员后查看1');
            }
            if ((float)$model_data['membership_price'] < 0.01){
                $this->error('当前分类不可购买,只能购买会员后查看2');
            }
            $goods_type = 'categories';
        }

        //查配置项1元=多少积分
        $score_exchange_rate = Config::where('name','score_exchange_rate')->value('value');
        $membership_score = bcmul($model_data['membership_price'],$score_exchange_rate,2);
        $res = [
            [
                'id' => $model_data['id'],
                'membership_expiry' => $model_data['membership_duration'],
                'membership_price' => $model_data['membership_price'],//金额
                'membership_score' => $membership_score,//需要花费的积分
                'name' => $name,
                'permission_description' => "{$name}{$model_data['membership_price']}(元)/{$membership_score}(积分)",//用户权限说明
                'status' => 'normal',//'normal','hidden'状态
                'status_text' => '启用',

                'goods_type'=>$goods_type,
                'table_name'=>$table_name,
                'goods_id'=>$goods_id,
            ]
        ];
        return $this->success('',$res);
    }





}
